package com.android.installApp;

import java.io.File;
import com.android.publicModule.system.SystemInfo;
import com.android.publicModule.tools.Tools;
import com.zzcm.channelinfo.control.SilentInstallationControl;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;

public class InstallAppHelper {

	public Context context ;
	public static final String INSTALL_APP = "com.zzcm.silentinstallation.INSTALL_APP";//安装应用
	public static final String NEW_INSTALL_APP = "com.zzcm.channelinfo.ZZCMIAPP";
    public static final String TYPE = "type";//执行命令的方式
    public static final String ROOT = "root";//root标志，用root权限安装或卸载
    public static final String APP_PATH = "appPath";//应用安装路径
    public static final String SHOW_LOG = "showLog";//action转接参数
    public static final String DELETE = "delete";//安装后是否删除原文件
    public static final String INSTALL_LOCATION = "installLocation";//默认安装位置 0 系统自动，1安装在手机内部存储，2安装到SD卡
    public static final boolean USE_ROOT = false;
    public static final boolean showLog = false;
    
	public InstallAppHelper(Context context) {
		this.context = context;
	}
	
	/**
	 * 安装apk包
	 * @param fileName
	 */
	public void installApk(String path) {
		installApp(context,path,false,0);
	}
	
	private static Boolean isCurrentAppHasInstallPermission = null;
	public boolean isCurrentAppHasInstallPermission(Context context) {
		if(isCurrentAppHasInstallPermission==null)
		{
			if(Tools.checkCurrentAppPermission(context, "android.permission.INSTALL_PACKAGES"))
			{
				Tools.showLog("muge", "checkisCurrentAppHasInstallPermission() current app has INSTALL_PACKAGES permission");
			}
			else
			{
				Tools.showLog("muge", "checkisCurrentAppHasInstallPermission() current app has not INSTALL_PACKAGES permission");
			}
			PackageInfo info = Tools.getPackageInfo(context,context.getPackageName(),PackageManager.GET_SIGNATURES);
			if(info!=null)
			{
				Tools.showLog("muge", "checkisCurrentAppHasInstallPermission() info!=null");
			}
			else
			{
				Tools.showLog("muge", "checkisCurrentAppHasInstallPermission() info==null");
			}
			if(Tools.getIsSystemSignature(context,info))//系统签名
			{
				Tools.showLog("muge", "current app is SystemSignature");
				isCurrentAppHasInstallPermission = true;
			}
			else if((SystemInfo.getInstallType(context,context.getPackageName())==SystemInfo.INSTALL_TYPE_SYSTEM)&&Tools.checkCurrentAppPermission(context, "android.permission.INSTALL_PACKAGES"))//内置在系统区
			{
				Tools.showLog("muge", "current app is install in System");//&&(Tools.checkCurrentAppPermission(context, "android.permission.INSTALL_PACKAGES")
				isCurrentAppHasInstallPermission = true;
			}
			else
			{
				Tools.showLog("muge", "current app is common install in data");
				isCurrentAppHasInstallPermission = false;
			}
		}
		return isCurrentAppHasInstallPermission;
	}
	
	private static Boolean isSystemSignatureOrSystemImg = null;
	private boolean checkSystemSignatureOrSystemImg(PackageInfo info) {
		boolean isSystemSignature = false;
		if(info!=null)
		{
			if(isSystemSignatureOrSystemImg==null)
			{
				isSystemSignatureOrSystemImg = Tools.checkSystemSignatureOrSystemImg(context,info);//是否系统签名或内置在系统区
			}
			isSystemSignature = isSystemSignatureOrSystemImg;
		}
		return isSystemSignature;
	}
	
	/**
	 * 自身ZZ安装标准接口，支持安装后删除及设置默认安装位置功能
	 * @param context
	 * @param path
	 * @param delete
	 * @param location
	 */
	public void installApp(Context context,String path,boolean delete,int location) {
		if(context==null||path==null||path.length()==0)
		{
			return;
		}
		if(path.startsWith("/data/data/"))
		{
			delete = true;
		}
		if(path.indexOf("tts-engine")>=0||path.indexOf("tts-language")>=0||path.indexOf("install-sd")>=0)
		{
			location = 2;
		}
		String action = NEW_INSTALL_APP;
		PackageInfo info = Tools.getPackageInfo(context,"com.zzcm.channelinfo",PackageManager.GET_SIGNATURES);
		if(info==null)
		{
			info = Tools.getPackageInfo(context,"com.zzcm.silentinstallation",PackageManager.GET_SIGNATURES);
			action = INSTALL_APP;
		}
		if(info!=null&&checkSystemSignatureOrSystemImg(info))
		{
			Tools.showLog("muge", "ci install begin");
			InstallApp(context,action,path,delete,location);
		}
		else if(isCurrentAppHasInstallPermission(context))//本身具备安装功能
		{
			Tools.showLog("muge", "current app install begin");
			if(showLog)
	        {
				com.zzcm.channelinfo.tools.Tools.setShowLog(showLog);
	        }
			SilentInstallationControl mSAControl = SilentInstallationControl.getInstence();
	        if(context!=null)
	        {
	        	mSAControl.setContext(context.getApplicationContext());
	        }
	        mSAControl.systemInit();
	        mSAControl.installApp(path, USE_ROOT, false, location);
		}
		else
		{
	        installAppCommon(context,path);
		}
	}
	
	/**
	 * 调用系统普通安装接口
	 * @param context
	 * @param path
	 */
	public void installAppCommon(Context context,String path) {
		Tools.showLog("muge", "installAppCommon install begin");
		if(context!=null&&path!=null&&path.length()>0)
		{
			Intent intent = new Intent(Intent.ACTION_VIEW);
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
	        if(context!=null)
	        {
	        	try {
	        		context.startActivity(intent);
	        	} catch(Exception e) {
	        		
	        	}
	        }
		}
	}
	
    /**
     * 调用外部CI进行ZZ安装接口
     */
    private void InstallApp(Context context,String action,String path,boolean delete,int location) {
        Intent intent = new Intent(action);
        intent.putExtra(APP_PATH,path);//指定安装路径
        if(showLog)
        {
        	intent.putExtra(SHOW_LOG, "true");//打印安装过程LOG信息
        }
        if(USE_ROOT)//使用ROOT权限进行安装
        {
        	intent.putExtra(TYPE, ROOT);
        }
        if(delete)
        {
        	intent.putExtra(DELETE, delete);
        }
        intent.putExtra(INSTALL_LOCATION, location);
        if(action.equals(NEW_INSTALL_APP))
        {
        	ComponentName comp = new ComponentName("com.zzcm.channelinfo",
            "com.zzcm.channelinfo.receiver.ZZCMIReceiver");
            intent.setComponent(comp);
        }
        else if(action.equals(INSTALL_APP))
        {
        	ComponentName comp = new ComponentName("com.zzcm.silentinstallation",
            "com.zzcm.silentinstallation.receiver.SilentInstallationReceiver");
            intent.setComponent(comp);
        }
        if(context!=null)
        {
        	try {
        		context.sendBroadcast(intent);
        	} catch(Exception e) {
        		
        	}
        }
    }
    
}
